package thread;

/**
 * @author: 成金乘
 * @date: 2023/1/5 14:48
 * @description:
 */
//编写代码, 实现阻塞队列案例
public class MyBlockingQueue {
    //定义数组
    private int[] t = new int[1000];
    //当前数组大小
    private int size = 0;
    //队首
    private int head = 0;
    //队尾
    private int tail = 0;

    //入队列
    public void put(int val) throws InterruptedException {
        synchronized (this){
            while(size == t.length){
                //满了,阻塞
                this.wait();
            }
            t[tail] = val;
            tail++;
            //处理tail
            if (tail >= t.length){
                tail = 0;
            }
            size++;
            this.notifyAll();
        }

    }

    //出队列
    public Integer take() throws InterruptedException{
        int index = 0;
        synchronized (this){
            while (size == 0){
                //队列空,阻塞
                this.wait();
            }
            index = t[head];
            head++;
            if (head >= t.length){
                head = 0;
            }
            size--;
            this.notifyAll();
        }
        return index;
    }

    public static void main(String[] args) {
        //实例化阻塞队列
        MyBlockingQueue queue = new MyBlockingQueue();
        //消费者模型
        Thread consumer = new Thread(()->{
           while(true){
               try{
                   int cons = queue.take();
                   System.out.println("消费了"+cons);
               }catch (InterruptedException e){
                   e.printStackTrace();
               }
           }
        });
        consumer.start();
        //生产者模型
        Thread producer = new Thread(()->{
            int count = 1;
            while(true){
                try{
                    System.out.println("生产了"+count);
                    queue.put(count);
                    count++;
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        producer.start();
    }
}
